package com.y2w.gulimall.order.web;

import com.y2w.common.exception.NoStockException;
import com.y2w.gulimall.order.service.OrderService;
import com.y2w.gulimall.order.vo.OrderConfirmVo;
import com.y2w.gulimall.order.vo.OrderSubmitVo;
import com.y2w.gulimall.order.vo.SubmitOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {

    @Autowired
    OrderService orderService;

    @GetMapping("/toTrade")
    public String toTrade(Model model, HttpSession session) throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo=orderService.confirmOrder();
        model.addAttribute("orderConfirmData",confirmVo);
        //显示订单确认的数据
        return "confirm";
    }

    /**
     * 下单功能
     * @param vo
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes redirectAttributes){
        SubmitOrderResponseVo responseVo= null;
        try {
            responseVo = orderService.submitOrder(vo);
        } catch (Exception e) {
            if(e instanceof NoStockException){
                responseVo=new SubmitOrderResponseVo();
                responseVo.setCode(3);
            }else{
                responseVo=new SubmitOrderResponseVo();
                responseVo.setCode(5);
            }
        }
        System.out.println("vo = " + vo);
        if(responseVo.getCode()==0){
        //    下单成功到支付选择页
            model.addAttribute("submitOrderResp",responseVo);
            return "pay";
        }else{
            String msg="下单失败：";
            switch (responseVo.getCode()){
                case 1: msg+="令牌校验失败";break;
                case 2: msg+="订单商品价格发生变化,请确认后再次提价";break;
                case 3: msg+="库存锁定失败";break;
                case 4: msg+="令牌不存在";break;
                case 5: msg+="服务出错";break;
            }
            redirectAttributes.addFlashAttribute("msg",msg);
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }
}
